package com.qst.controller;

import com.qst.pojo.entity.Order;
import com.qst.pojo.entity.Station;
import com.qst.repository.OrderRepository;
import com.qst.repository.StationRepository;
import com.qst.repository.UserRepository;
import com.qst.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据分析控制器
 */
@RestController
@RequestMapping("/api/analytics")
public class AnalyticsController {

    private static final Logger logger = LoggerFactory.getLogger(AnalyticsController.class);

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private StationRepository stationRepository;

    /**
     * 获取总体统计数据
     */
    @GetMapping("/overview")
    public Result<Map<String, Object>> getOverview() {
        try {
            Map<String, Object> overview = new HashMap<>();
            
            // 获取订单总数
            long totalOrders = orderRepository.count();
            
            // 获取总收入（只统计已完成订单的金额）
            double totalRevenue = orderRepository.findAll().stream()
                    .filter(order -> order.getStatus() == Order.OrderStatus.completed)
                    .mapToDouble(order -> order.getTotalAmount() != null ? order.getTotalAmount().doubleValue() : 0)
                    .sum();
            
            // 获取总重量
            double totalWeight = orderRepository.findAll().stream()
                    .mapToDouble(order -> order.getTotalWeight() != null ? order.getTotalWeight().doubleValue() : 0)
                    .sum();
            
            // 获取活跃用户数（客户）
            long activeCustomers = userRepository.findAll().stream()
                    .filter(user -> "customer".equals(user.getRole().toString()))
                    .count();
            
            // 站点数量
            long totalStations = stationRepository.count();
            
            overview.put("totalOrders", totalOrders);
            overview.put("totalRevenue", totalRevenue);
            overview.put("totalWeight", totalWeight);
            overview.put("activeCustomers", activeCustomers);
            overview.put("totalStations", totalStations);
            
            // 添加趋势数据（示例：这里设置为固定值，实际应该根据历史数据计算）
            overview.put("ordersTrend", 12.5);
            overview.put("revenueTrend", 8.3);
            overview.put("weightTrend", 15.2);
            overview.put("customersTrend", 5.6);
            
            return Result.success(overview);
        } catch (Exception e) {
            logger.error("获取总体统计数据失败", e);
            return Result.error("获取统计数据失败");
        }
    }

    /**
     * 获取订单趋势数据
     */
    @GetMapping("/orders-trend")
    public Result<Map<String, Object>> getOrdersTrend(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate
    ) {
        try {
            // 这里应该根据日期范围查询真实数据
            // 示例：返回简化的数据结构
            Map<String, Object> trendData = new HashMap<>();
            
            // 实际应该从数据库查询按日期分组的订单数据
            // 这里先返回基本统计
            long totalOrders = orderRepository.count();
            trendData.put("total", totalOrders);
            
            return Result.success(trendData);
        } catch (Exception e) {
            logger.error("获取订单趋势失败", e);
            return Result.error("获取订单趋势失败");
        }
    }

    /**
     * 获取收入趋势数据
     */
    @GetMapping("/revenue-trend")
    public Result<Map<String, Object>> getRevenueTrend(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate
    ) {
        try {
            Map<String, Object> trendData = new HashMap<>();
            
            double totalRevenue = orderRepository.findAll().stream()
                    .mapToDouble(order -> order.getTotalAmount() != null ? order.getTotalAmount().doubleValue() : 0)
                    .sum();
            
            trendData.put("total", totalRevenue);
            
            return Result.success(trendData);
        } catch (Exception e) {
            logger.error("获取收入趋势失败", e);
            return Result.error("获取收入趋势失败");
        }
    }

    /**
     * 获取站点统计数据
     */
    @GetMapping("/stations-stats")
    public Result<Map<String, Object>> getStationsStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            long totalStations = stationRepository.count();
            long activeStations = stationRepository.findAll().stream()
                    .filter(station -> "active".equals(station.getStatus().toString()))
                    .count();
            long busyStations = stationRepository.findAll().stream()
                    .filter(station -> "busy".equals(station.getStatus().toString()))
                    .count();
            long closedStations = stationRepository.findAll().stream()
                    .filter(station -> "closed".equals(station.getStatus().toString()))
                    .count();
            
            stats.put("total", totalStations);
            stats.put("active", activeStations);
            stats.put("busy", busyStations);
            stats.put("closed", closedStations);
            
            return Result.success(stats);
        } catch (Exception e) {
            logger.error("获取站点统计失败", e);
            return Result.error("获取站点统计失败");
        }
    }

    /**
     * 获取站点排行（按订单量）
     */
    @GetMapping("/stations-ranking")
    public Result<List<Map<String, Object>>> getStationsRanking() {
        try {
            // 获取所有站点
            List<Station> stations = stationRepository.findAll();
            
            // 获取所有订单
            List<Order> orders = orderRepository.findAll();
            
            // 统计每个站点的订单数量
            Map<Integer, Long> stationOrderCount = new HashMap<>();
            for (Order order : orders) {
                Integer stationId = order.getStationId();
                stationOrderCount.put(stationId, stationOrderCount.getOrDefault(stationId, 0L) + 1);
            }
            
            // 构建排行榜数据
            List<Map<String, Object>> ranking = new ArrayList<>();
            for (Station station : stations) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", station.getId());
                item.put("name", station.getName());
                item.put("address", station.getAddress());
                item.put("orderCount", stationOrderCount.getOrDefault(station.getId(), 0L));
                ranking.add(item);
            }
            
            // 按订单数量降序排序，取前5名
            ranking.sort((a, b) -> {
                Long countA = (Long) a.get("orderCount");
                Long countB = (Long) b.get("orderCount");
                return countB.compareTo(countA);
            });
            
            // 只返回前5名
            if (ranking.size() > 5) {
                ranking = ranking.subList(0, 5);
            }
            
            return Result.success(ranking);
        } catch (Exception e) {
            logger.error("获取站点排行失败", e);
            return Result.error("获取站点排行失败");
        }
    }

    /**
     * 获取订单状态统计
     */
    @GetMapping("/orders-status-stats")
    public Result<List<Map<String, Object>>> getOrdersStatusStats() {
        try {
            // 获取所有订单
            List<Order> orders = orderRepository.findAll();
            
            // 统计各状态的订单数量
            Map<String, Long> statusCount = orders.stream()
                    .collect(Collectors.groupingBy(
                            order -> order.getStatus().toString(),
                            Collectors.counting()
                    ));
            
            // 构建返回数据
            List<Map<String, Object>> stats = new ArrayList<>();
            
            // 定义所有状态及其对应的中文标签
            String[][] statusLabels = {
                    {"pending", "待确认"},
                    {"confirmed", "已确认"},
                    {"in_progress", "进行中"},
                    {"completed", "已完成"},
                    {"cancelled", "已取消"}
            };
            
            for (String[] statusLabel : statusLabels) {
                Map<String, Object> item = new HashMap<>();
                item.put("name", statusLabel[0]);
                item.put("label", statusLabel[1]);
                item.put("count", statusCount.getOrDefault(statusLabel[0], 0L));
                stats.add(item);
            }
            
            return Result.success(stats);
        } catch (Exception e) {
            logger.error("获取订单状态统计失败", e);
            return Result.error("获取订单状态统计失败");
        }
    }
}

